import { getUserGuideStorage, creatUserGuideStorage } from '@src/api/GuideApi';
import { storageGet, storageSet, storageRemove } from '@src/util/storageV2';
interface userGuideStorageItem {
	type: string, // 缓存key
	isComplete: number, // 是否已经完成
	step: number, // 当前步骤
}
interface setUserStorage {
	userGuideList: Array<userGuideStorageItem>
}

/**
 * @des 处理引导提示缓存 存储全局的引导相关参数并同步至本地缓存之中
 */
export function getUserGuideStorageBase() {
  // let localStash = storageGet('user-guide-storage');
  // if (localStash) {
  // 	return Promise.resolve(JSON.parse(localStash))
  // }
  return getUserGuideStorage()
    .then(res => {
      if (res.code == 0 || res.status == 0) {
        const returnObj: any = {};
        try {
          res.data.forEach((item: any) => {
            if (item.isComplete < 0) {
              // 引导已经失效不再同步到本地缓存对应前端代码也应该注释或者删除
              if (storageGet(item.type)) {
                // 如果用户之前存在已经失效的本地缓存需要清理
                storageRemove(item.type);
              }
              return
            }
            const { step, isComplete, type } = item;
            returnObj[type] = {
              step,
              isComplete
            }
          })
        } catch (error) {
          console.warn(error, 'error try catch');
        }
        // storageSet('user-guide-storage', JSON.stringify(returnObj))
        return returnObj;
      } 
      throw res;
			
    })
    .catch(err => {
      console.warn('http erro', err);
      return null
    })
    .finally(() => { });
}
/**
 * @des 更新当前用户的引导缓存数据
 * @returns 
 */
export function setUserGuideStorageBase(options: setUserStorage, userGuideStroage:any = {}) {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await creatUserGuideStorage(options);
      if (res.code == 0 || res.status == 0) {
        // let localStash = storageGet('user-guide-storage');
        // let stashObj: any = localStash || {};
        const stashObj: any = userGuideStroage || {};
        options.userGuideList.forEach(item => {
          const { step, isComplete } = item;
          stashObj[item.type] = {
            step,
            isComplete
          }
        })
        // storageSet('user-guide-storage', JSON.stringify(stashObj));
        resolve(stashObj);
      }
    } catch (error) {
      console.warn(error, 'error try catch');
      reject(null)
    }
  })
}
